var jweixin = require('./jssdk.js');
import Cfg from './config.js';
import Net from './request.js';
export default {
	//判断是否在微信中    
	isWechat: function() {
		var ua = window.navigator.userAgent.toLowerCase();
		if (ua.match(/micromessenger/i) == 'micromessenger') {
			//console.log('是微信客户端')  
			return true;
		} else {
			//console.log('不是微信客户端')  
			return false;
		}
	},	
	// 初始化
	initJssdk: function(callback) {		
		if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
			window.entryUrl = location.href.split('#')[0]
		}
		let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); 	
		let signLink = isiOS ? window.entryUrl : location.href.split('#')[0];		
		var uri = encodeURIComponent(signLink); 							
		Net._get('getSignPackage',{url:uri},res=>{			
			let data = res.data;
			jweixin.config({
				debug: false,
				appId: data.appId,
				timestamp: data.timestamp,
				nonceStr: data.nonceStr,
				signature: data.signature,
				jsApiList: ['chooseWXPay']
			});			
			jweixin.ready(function() {						
				if (callback) {
					callback();
				}
			})
		});		
	},	
	// 初始化
	initJssdkShare: function(callback) {		
		if (typeof window.entryUrl === 'undefined' || window.entryUrl === '') {
			window.entryUrl = location.href.split('#')[0]
		}
		let isiOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); 	
		let signLink = isiOS ? window.entryUrl : location.href.split('#')[0];		
		var uri = encodeURIComponent(signLink); 							
		Net._get('getSignPackage',{url:uri},res=>{			
			let data = res.data;
			jweixin.config({
				debug: false,
				appId: data.appId,
				timestamp: data.timestamp,
				nonceStr: data.nonceStr,
				signature: data.signature,
				jsApiList: ['checkJsApi',
                            'onMenuShareTimeline',
                            'onMenuShareAppMessage']
			});			
			jweixin.ready(function() {						
				if (callback) {
					callback();
				}
			})
		});		
	},
	//微信分享
	wxShare:function(data){
		if (!this.isWechat()) {
			return;
		}
		//每次都需要重新初始化配置，才可以进行分享  
		this.initJssdkShare(function(signData) {
			jweixin.ready(function() {
				var shareData = {
					title: data && data.title ? data.title : signData.site_name,
					desc: data && data.desc ? data.desc : signData.site_description,
					link: data.url,
					imgUrl: data && data.img ? data.img : signData.site_logo,
					success: function(res) {
						// 分享后的一些操作,比如分享统计等等
					},
					cancel: function(res) {
						
					}
				};
				//分享给朋友接口  
				jweixin.onMenuShareAppMessage(shareData);
				//分享到朋友圈接口  
				jweixin.onMenuShareTimeline(shareData);
			});
		});
	},
	//微信支付  
	wxPay: function(params = {},ok,fail) {
		if (!this.isWechat()) {			
			return;
		}
		this.initJssdk(function() {			
			jweixin.chooseWXPay({
				timestamp: params.timeStamp, 
				nonceStr: params.nonceStr,
				package: params.package,
				signType: params.signType, 
				paySign: params.paySign, 
				success: function(res) {
					ok(res)					
				},
				cancel: function(res) {
					fail(res)									
				},				
			});

		});
	},
	wxUrlCode:function () {
		var url = location.search;		
		var theRequest = new Object();
		if (url.indexOf('?') != -1) {
			var str = url.substr(1);
			var strs = str.split('&');
			for (var i = 0; i < strs.length; i++) {
				theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1];
			}
		}
		return theRequest;
	},	
	wxGetAppId:function(cb){		
		Net._get('getAppId',null,res=>{
			if(res.code == 1)cb && cb(res.data);
			else cb && cb('');						
		},true)
	},	
	wxAuthorize:function() {		
		let local = window.location.href; 	
		let code = this.wxUrlCode().code; // 截取code		
		let oldCode = uni.getStorageSync('wechatCode')		
		this.wxGetAppId(appid=>{			
			if (code == null || code === '' || code == 'undefined' || code == oldCode) {
				let uri = encodeURIComponent(local)			
				uni.setStorageSync('wechatCode',0)
				window.location.href =
					`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`
			} else {			
				uni.setStorageSync('wechatCode',code)			
				Net._get('accesstoken',{code:code},res=>{					
					uni.setStorageSync('wechatOpenId',res.data);
				})			
			}			
		})		
	},
	wxAuthLogin:function() {
		let local = window.location.href; 
		let code = this.wxUrlCode().code; // 截取code		
		let oldCode = uni.getStorageSync('wechatCode')
		this.wxGetAppId(appid=>{			
			if (code == null || code === '' || code == 'undefined' || code == oldCode){
				let uri = encodeURIComponent(local)
					uni.setStorageSync('wechatCode',0)
					window.location.href=`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect`
			}
		})
	},
	wxLogin:function(){
		let code = this.wxUrlCode().code; // 截取code
		let oldCode = uni.getStorageSync('wechatCode')
		if (code == null || code === '' || code == 'undefined' || code == oldCode){			
			return;
		}
		uni.setStorageSync('wechatCode',code)	
		let fid = Cfg.getParentId();		
		Net._get('loginByCode',{code:code,fid:fid},res=>{
			
			Cfg.login(res.data.token);
			
			Msg.Success('登录成功！',()=>{
				Nav._to({url:'/pages/index/index',type:2})
			})					
		})						
	},
	wxCode2openid:function(code,cb){		
		Net._get('code2openid',{code:code},res=>{
			cb(res);
		},true);		
	}	
}